package cn.codecang.mall.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.jetbrains.annotations.NotNull;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * JWTUtil
 *
 * @author xiaoluo
 * @date 2023/6/2 15:09
 */
public class JWTUtil {
    /**
     * 秘钥
     */
    private static final String SECRET = "code_cang_mall_jwt";
    /**
     * 过期时间 (小时)
     */
    private static final Integer EXPIRATION_TIME = 24;

    /**
     * 生成token
     *
     * @param payload token信息
     * @return {@code String} token
     */
    public static String generateToken(@NotNull Map<String, String> payload) {
        // 指定token过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, EXPIRATION_TIME);
        JWTCreator.Builder builder = JWT.create();
        // 构建token数据
        payload.forEach(builder::withClaim);
        // 生成签名
        return builder.withIssuedAt(new Date())
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 解析token
     *
     * @param token 令牌
     * @return {@code DecodedJWT}
     */
    public static DecodedJWT decodeToken(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }
}
